/**
 * 用来处理路由守卫的功能
 * @author kjx
 */
import router from "../index";
//进度条 不支持ts类型所以存在红色
import nprogress from "nprogress";
//用记pinia
import pinia from "@/store";
import { userStore } from "@/store/module/acl/user";
// 获取通用设置里面的标题信息
import setting from "@/setting/setting";

//进度条样式
import "nprogress/nprogress.css";
//去掉加载时的 读条
nprogress.configure({ showSpinner: false });
let userinfo = userStore(pinia);

//全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  document.title = `${setting.title} - ${to.meta.title}`;
  //用来处理token令牌
  let token = userinfo.token;

  let username = userinfo.username;

  //对于token的处理，存在直接放行
  if (token) {
    if (to.path == "/login") {
      next();
    } else {
      if (username) {
        next();
      } else {
        //如果没有获取到当前用户信息，那么要重新获取一次用户信息
        try {
          await userinfo.userInformation();
          next();
        } catch (error) {
          //token失效
          //用户csrf
          userinfo.userLogout();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
    //不存在进行判断，如果为login那么放行
  } else {
    if (to.path == "/login") {
      next();
      //不成功以后直接转换成登陆页面，然后再转向真实数据页面
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
  // 路由访问开始进度条
  nprogress.start();
});

//全局后置守卫
router.afterEach((to: any, from: any, next: any) => {
  //用来处理路由完成以后的处理

  //处理完成以后关闭进度条
  nprogress.done();
});
